﻿using Se.Net.Sockets.Protocol;
using Google.ProtocolBuffers.Descriptors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using Se.Extend;
using Se.ProtoBuf.T4Template;

namespace Se.Protocol.MessageHandle.ProtoBuf
{
    /// <summary>
    /// ProtoBuf Factory
    /// </summary>
    public static class ProtoBufFactory
    {

        public const string CodeFileName = "";

        //public const string 

        static ProtoBufFactory()
        {
            List<MessageDescriptor> ServerMessages = new List<MessageDescriptor>();
            var login = new Login.Builder();
            var protoServerMsg = Game.Descriptor.MessageTypes.FirstOrDefault(message => message.Name == "ServerMessage");
            var protoMsgSet = protoServerMsg.Fields.Where(message => !message.GetType().IsEnum);
            foreach (var protoMsg in protoMsgSet)
            {
                if (protoMsg.FieldType != FieldType.Message) continue;
                var msg = Game.Descriptor.MessageTypes.FirstOrDefault(c => c.Name == protoMsg.MessageType.Name);
                ServerMessages.Add(msg);

                msg.Fields.OrderBy(c => c.FieldNumber);
                foreach (var field in msg.Fields.OrderBy(c => c.FieldNumber))
                {
                    
                }
            }

            foreach (var msgItem in ServerMessages)
            {
                StringBuilder sbMethodCode = new StringBuilder();
                sbMethodCode = new StringBuilder("    void ");
                sbMethodCode.Append("PtResponse_").Append(msgItem.Name.ToLowerFirst()).Append("(");
                foreach (var parameter in msgItem.Fields)
                {
                    // TODO 自定义数据格式和枚举处理
                    if (parameter.FieldType == FieldType.Enum)
                    {

                    }
                    else if (parameter.FieldType == FieldType.Message)
                    { }
                    else
                    {
                        sbMethodCode.Append(parameter.FieldType.ToString()).Append(" ").Append(parameter.Name).Append(", ");
                    }
                }
                if (msgItem.Fields.Count > 0) sbMethodCode.Remove(sbMethodCode.Length - 2, 2);
                sbMethodCode.Append(");");

            }

        }

        static void MessageHandler(string name, ServerMessage package)
        {
            var messageType = package.Type;
            var field = package[ServerMessage.Descriptor.FindFieldByNumber((int)messageType)];


            MyTemplate template = new MyTemplate();
            template.TransformText();
        }


    }
    public partial class MessageInterfaceTemplate
    {

    }

}
